<?php

namespace app\index\controller;

use app\common\controller\HomeBase;
use app\common\model\Article;
use app\common\model\Praise;
use app\common\model\Site;
use app\common\model\User;
use app\common\model\PseudoOriginal;
use app\common\model\Ad;
use app\common\model\AdCategory;
use app\common\model\ArticleCategory;
use app\common\model\SiteCategory;
use app\common\model\News;
use app\common\model\UrlClickLog;
use app\common\model\FriendlyLink;
use think\Cache;
use phpanalysis\phpanalysis;
use think\Request;
use think\response\Json;

class Index extends HomeBase
{
    protected $siteConfig;

    public function _initialize()
    {
        parent::_initialize();
        $action = Request::instance()->action();
//        if ($action == 'changeinfo') $action = 'index';
        $this->assign('action', $action);
        $this->siteConfig = Cache::get('site_config');
    }

    public function index()
    {
        $homnePageShowArr = explode(',', $this->siteConfig['home_page_show']);
        if (in_array(1, $homnePageShowArr)) {
            //本月冠军
            $whereMonth['a.status'] = 1;
            $whereMonth['publish_time'] = ['gt', date('Y-m-01')];
            $monthPostTop = (new Article())->alias('a')->join('user u', 'u.id=a.user_id')->where($whereMonth)->field('u.*,count(*) as count')->group('u.id')->order('count desc')->limit(10)->select();
            $this->assign('monthPostTop', $monthPostTop);
            //近期投稿
            $whereNewPost['a.status'] = 1;
            $newPostTop = (new Article())->alias('a')->join('user u', 'u.id=a.user_id')->where($whereNewPost)->field('u.*,publish_time')->group('u.id')->order('publish_time desc')->limit(10)->select();
            $this->assign('newPostTop', $newPostTop);
        }
        $this->assign('homnePageShowArr', $homnePageShowArr);
        //轮播
        $carousel = (new Article())->where('is_carousel', 1)
            ->where('status', 1)->order('sort', 'desc')
            ->limit(5)->select();
        $this->assign('carousel', $carousel);

        //最近更新
        $newArticles = (new Article())->where('status', 1)
            ->order('is_ad', 'desc')->order('sort', 'desc')
            ->order('publish_time', 'desc')
            ->field('id,title,is_ad,is_essence,out_link,publish_time,color')
            ->limit(26)->select();
        $this->assign('newArticles', $newArticles);
        //本月冠军
        $monthRank = Article::all(function ($query) {
            $query->where('status', 1)->where('is_ad', 0)->where('out_link', '')->limit(14)->order('month_view', 'desc');
        });
        //总冠军
        $totalRank = Article::all(function ($query) {
            $query->where('status', 1)->where('is_ad', 0)->where('out_link', '')->limit(14)->order('total_view', 'desc');
        });
        //随机推荐
        $recommend = (new Article())->where('status', 1)->where('is_ad', 0)->where('out_link', '')->orderRaw('rand()')->limit(6)->select();

        //板块更新展示
        $articleCategory = (new ArticleCategory())->where('status', 1)
            ->order('sort desc')->field('id,name,alias_name')->select()->toArray();
        $chunk_result = array_chunk($articleCategory, 3);
        $categoryTeam1 = $chunk_result[0];
        foreach ($categoryTeam1 as $k => $v) {
            $categoryTeam1[$k]['artlists'] = Article::getListByCategoryId($v['id'], 7);
        }
        $categoryTeam2 = $chunk_result[1];
        foreach ($categoryTeam2 as $k => $v) {
            $categoryTeam2[$k]['artlists'] = Article::getListByCategoryId($v['id'], 7);
        }

        $this->assign('categoryTeam1', $categoryTeam1);
        $this->assign('categoryTeam2', $categoryTeam2);
        //友链
        $friendlinks = (new FriendlyLink())->where('status', 1)->order('sort', 'desc')->select();
        //广告
        $ad1 = AdCategory::getAdListByLocationId(1);
        $ad2 = AdCategory::getAdListByLocationId(2);
        $ad5 = AdCategory::getAdListByLocationId(5);
        $ad6 = AdCategory::getAdListByLocationId(6);
        $this->assign('friendlinks', $friendlinks);
        $this->assign('ad', $ad1);
        $this->assign('ad2', $ad2);
        $this->assign('ad5', $ad5);
        $this->assign('ad6', $ad6);
        $this->assign('monthRank', $monthRank);
        $this->assign('totalRank', $totalRank);
        $this->assign('recommend', $recommend);
        return view();
    }

    public function tools()
    {
        //免费工具
        $tools = Tool::all(function ($query) {
            $query->where('status', 1)->order('id', 'desc');
        });
        //广告
        $ad = AdCategory::getAdListByLocationId(4);

        $this->assign('ad', $ad);
        $this->assign('tools', $tools);
        return view();
    }

    public function errors()
    {
        return view();
    }

    public function noteClickLog($id)
    {
        $ip = $this->request->ip();
        $_data['url_id'] = $id;
        $_data['ip'] = $ip;
        $_data['click_time'] = time();
        UrlClickLog::create($_data);
    }


    public function detail()
    {
        $id = is_number(input('id')) ? input('id') : '';
        if (empty($id)) {
            return $this->error('亲！你迷路了', 'index/index/index');
        } else {
            $articleModel = new Article();
            //先判断是不是外链
            $find = $articleModel->find($id);
            if (!$find || $find->status != 1) {
                $this->redirect(url('index/index/index'));
            }
            if ($find->out_link) {
                $this->redirect($find->out_link);
            }
            $article = $articleModel->alias('a')
                ->join('article_category b', 'a.category_id=b.id', 'left')
                ->join('user c', 'a.user_id=c.id', 'left')
                ->field('a.*,b.name,c.nickname,c.uuid,c.avatar')->where('a.status', 1)->where('a.id', $id)->find();
            if (!$article) {
                return $this->error('该页面不存在或暂时无权查看', 'index/site/index');
            }

            $authorWhere['status'] = ['gt', 0];
            $authorWhere['id'] = $article->user_id;
            $authorInfo = (new User())->where($authorWhere)->find();
            $this->assign('authorInfo', $authorInfo);
            if (!$authorInfo) {
                return $this->error('亲！该作者状态异常，所以其名下投稿也暂时不能访问', 'index/index/index');
            }
            //增加阅读量
            $article->month_view += 1;
            $article->total_view += 1;
            $article->save();
            $category = (new ArticleCategory())->find($article->category_id);
            if (empty($category)) {
                $cateName = '未分类';
            } else {
                $cateName = $category->name;
            }
            $article->categoryName = $cateName;

            $ad = AdCategory::getAdListByLocationId(5);
            $this->assign('ad', $ad);
            if ($article) {
                //查询同类
                $kinds = (new Article())->where('status', 1)->where('category_id', $article->category_id)->orderRaw('rand()')->limit(4)->select();
                $this->assign('kinds', $kinds);
                $rands = (new Article())->alias('a')->join('article_category b', 'a.category_id=b.id', 'left')
                    ->where('a.status', 1)->orderRaw('rand()')
                    ->limit(10)->field('a.*,b.name')->select();
                $this->assign('rands', $rands);
                $this->assign('article', $article);
                $tpl = $article->has_attachment ? 'soft' : 'article';
                $isPraise = Praise::checkIsPraised(1, $id, session('userid'), $this->request->ip());
                $hasPraised = 0;
                if ($isPraise) {
                    $hasPraised = 1;
                }
                $this->assign('hasPraised', $hasPraised);

                //重新写hover
                $URI = '/list/' . $article->category_id . '.html';
                $this->assign('URI', $URI);
                $this->assign('action', $tpl);
                return view('index_' . $tpl);
            } else {
                return $this->error('亲！你迷路了', 'index/index/index');
            }
        }
    }


    public function lists()
    {
        $id = is_number(input('id')) ? input('id') : 'all';
        if ($id == 'all') {
            $category['name'] = '全部资源';
            $map = [];
        } else {
            $map['category_id'] = $id;
            $category = (new ArticleCategory())->find($id);
        }
        $articles = (new Article())->alias('a')
            ->join('article_category b', 'a.category_id=b.id', 'left')
            ->join('user c', 'a.user_id=c.id')
            ->where($map)->where("a.status", 1)
            ->order('id', 'desc')
            ->field('a.*,b.name,c.nickname')
            ->paginate(10);
        $count = (new Article())->where("status", 1)->where($map)->count();
        $ad = AdCategory::getAdListByLocationId(2);
        $this->assign('ad', $ad);
        $this->assign('count', $count);
        $this->assign('articles', $articles);
        $this->assign('category', $category);
        return view();
    }

    public function rank()
    {
        $rankType = input('rank_type') ? input('rank_type') : 'day';
        if ($rankType == 'all') {
            $type = 'total';
        } elseif ($rankType == 'month') {
            $type = 'month';
        } else {
            $type = 'day';
        }
        $viewType = $type . "_view";
        //排行榜条数
        $ranks = (new Article())->order($viewType, 'desc')->limit(30)->column('id,link,title,logo_path,site_short_content,' . $viewType . ' as view');
        $this->assign('ranks', $ranks);
        return view();
    }

    public function search($keyword)
    {
        $keyword = remove_xss($keyword);
        $category['name'] = '搜索结果';
        $this->assign('keyword', $keyword);
        $articles = (new Article())->alias('a')
            ->join('article_category b', 'a.category_id=b.id', 'left')
            ->join('user c', 'a.user_id=c.id')
            ->where("a.status", 1)->where('title', 'like', '%' . $keyword . '%')
            ->order('id', 'desc')->field('a.*,b.name,c.nickname')->paginate(10, false, $config = ['query' => array('keyword' => $keyword)]);
        $count = (new Article())->where("status", 1)->where('title', 'like', '%' . $keyword . '%')->count();


        $ad = AdCategory::getAdListByLocationId(2);
        $this->assign('action', 'search_result');
        $this->assign('ad', $ad);
        $this->assign('count', $count);
        $this->assign('articles', $articles);
        $this->assign('category', $category);

        return view('index_lists');

    }

    public function test()
    {
        //PseudoOriginal

//        $spinner = new PseudoOriginal();
////        $text = '你好，大佬，覆盖好广啊';
////        echo $spinner->replace($text);
//        Article::createCacheJson();

        $str = '1年爱奇艺黄金会员';
        $pa = new PhpAnalysis($str);
//        $pa::$loadInit = false;
//        $pa->LoadDict();
//        $pa->SetSource($str);
        $pa->StartAnalysis();
        $tags = $pa->GetFinallyResult();
        var_dump($tags);
    }

    public function getemotion()
    {
        $path = WEB_URL . '/public/plugins/wangEditor/emotion/';
        $dir = ROOT_PATH . 'public' . DS . 'plugins' . DS . 'wangEditor' . DS . 'emotion' . DS;
        $array = array();
        foreach (glob($dir . '*', GLOB_ONLYDIR) as $files) {
            $files1 = iconv('GB2312', 'UTF-8', $files);
            $filename = basename($files1);
            $k = $filename;
            $array[$k]['title'] = $filename;
            if (is_dir($files)) {
                $array[$k]['data'] = array();
                if ($dh = opendir($files)) {
                    while (($file = readdir($dh)) !== false) {
                        if ($file != "." && $file != "..") {
                            $result = pathinfo($file);
                            $file = iconv('GB2312', 'UTF-8', $file);
                            $n = str_replace('.' . $result['extension'], '', $file);
                            array_push($array[$k]['data'], array('icon' => $path . $filename . '/' . $file, 'value' => $n));
                        }
                    }
                    closedir($dh);
                }
            }
        }
        return json_encode($array);
    }
}
